package com.twxm.breed.iot;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.exceptions.ClientException;
import com.twxm.breed.entity.DeviceInfo;
import com.twxm.breed.entity.EventLog;
import com.twxm.breed.entity.FishPond;
import com.twxm.breed.service.EventLogService;
import com.twxm.breed.service.FishPondService;
import com.twxm.breed.util.JsonResult;
import com.twxm.breed.util.WXMsgSender;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class OxygenTaskManager {
    public static EventLogService eventLogService;
    public static FishPondService fishPondService;
    // 溶氧量的task
    // 比较特殊，启动之后要检查数据库，把开启状态的设备，执行task
    // 所以这里用一个HashSet来保存需要检测的设备
    HashMap<String, OxygenTaskInfo> pondOxygenTaskMap = new HashMap<>();
    private ScheduledExecutorService executor; // 定时任务执行器

    private static OxygenTaskManager instance;

    public static OxygenTaskManager getInstance(){
        if(instance == null){
            instance = new OxygenTaskManager();
        }
        return instance;
    }


    public OxygenTaskManager(){
        this.executor = Executors.newSingleThreadScheduledExecutor();
        executor.scheduleAtFixedRate(() -> {
            this.run();
        }, 5, 5, TimeUnit.SECONDS);
    }

    public void run(){
        pondOxygenTaskMap.forEach((pondId, oxygenTaskInfo)->{
            try {
                oxygenTaskInfo.run();
            } catch (ClientException | IOException e) {
                throw new RuntimeException(e);
            }
        });
    }

    public void addPond(String pondId, DeviceInfo oxygenDevice, DeviceInfo zengyangDevice, float upper, float lower){
        // 添加一个监控的鱼塘
        OxygenTaskInfo o = new OxygenTaskInfo(pondId, oxygenDevice.getCategoryInfo().getProductKey(), oxygenDevice.getDeviceId(), zengyangDevice.getCategoryInfo().getProductKey(), zengyangDevice.getDeviceId(), upper, lower);
        pondOxygenTaskMap.put(pondId, o);
    }

    public void removePond(String pondId){
        // 移除一个监控的鱼塘
        if(!pondOxygenTaskMap.containsKey(pondId)){
            return;
        }
        pondOxygenTaskMap.remove(pondId);
    }

    public boolean changeUpperAndLower(String pondId, float upper, float lower){
        // 改变上下限
        if(!pondOxygenTaskMap.containsKey(pondId)){
            return false;
        }
        OxygenTaskInfo o = pondOxygenTaskMap.get(pondId);
        o.changeUpperAndLower(upper, lower);
        return true;
    }
}
class OxygenTaskInfo{
    public String pondId;
    public String rongyangProductKey;
    public String rongyangDeviceId;
    public String zengyangProductKey;
    public String zengyangDeviceId;
    public float upper;
    public float lower;
    public long lastestWarningSeconds;


    public OxygenTaskInfo(String pondId, String rongyangProductKey, String rongyangDeviceId, String zengyangProductKey, String zengyangDeviceId, float upper, float lower) {
        this.pondId = pondId;
        this.rongyangProductKey = rongyangProductKey;
        this.rongyangDeviceId = rongyangDeviceId;
        this.zengyangProductKey = zengyangProductKey;
        this.zengyangDeviceId = zengyangDeviceId;
        this.upper = upper;
        this.lower = lower;
        this.lastestWarningSeconds = 0;
    }

    public void changeUpperAndLower(float upper, float lower){
        this.upper = upper;
        this.lower = lower;
    }

    public void run() throws ClientException, IOException {
        String valueStr = ALiYunIOTAPI.getInstance().queryProperty(rongyangProductKey, rongyangDeviceId, "oxygen");
        float value = Float.parseFloat(valueStr);
        if(value < lower){
            ALiYunIOTAPI.getInstance().setDeviceOpen(zengyangProductKey, zengyangDeviceId);
            if(System.currentTimeMillis() / 1000 - this.lastestWarningSeconds < 1800){
                return;
            }
        }else if(value > upper){
            ALiYunIOTAPI.getInstance().setDeviceClose(zengyangProductKey, zengyangDeviceId);
            if(System.currentTimeMillis() / 1000 - this.lastestWarningSeconds < 1800){
                return;
            }
        }else{
            return;
        }
        // 警报
        this.lastestWarningSeconds = System.currentTimeMillis() / 1000;
        JSONObject data = new JSONObject();
        data.put("pondId", this.pondId);
        data.put("oxygen", String.valueOf(value));
        data.put("upper", String.valueOf(upper));
        data.put("lower", String.valueOf(lower));
        JsonResult result = WXMsgSender.getInstance().sendMsg(data);
        System.out.println("SendMsgResult" + result.getCode() + ":" + result.getMessage() + ":" + result.getData().toString());
        FishPond fishPond = OxygenTaskManager.fishPondService.selectById(pondId);
        EventLog eventLog = new EventLog(fishPond,new Date(),upper,lower,value);
        Map<String,Object> map = new HashMap<>();
        map.put("alarmTime",new Date());
        map.put("lower",lower);
        map.put("upper",upper);
        map.put("oxygen",value);
        map.put("pondId",pondId);
        OxygenTaskManager.eventLogService.addEvent(map);
    }
}

